"use server";
import { sendResetPasswordEmail } from "./../lib/mail";
import { getUserByEmail } from "@/data/user";
import { ResetPasswordSchema } from "@/schemas";
import * as z from "zod";
import { generateResetPasswordToken } from "./token";
export const reset = async (values: z.infer<typeof ResetPasswordSchema>) => {
  const validateFilelds = ResetPasswordSchema.safeParse(values);
  if (!validateFilelds) {
    return {
      code: 1,
      data: "Invalid fields",
      message: "Invalid fields",
    };
  }
  const { email } = validateFilelds.data!;
  const user = await getUserByEmail(email);
  if (!user) {
    return {
      code: 1,
      data: "Email not found",
      message: "Email not found",
    };
  }
  // 生成token
  const passwordResetToken = await generateResetPasswordToken(email);
  await sendResetPasswordEmail(
    passwordResetToken.email,
    passwordResetToken.token
  );
  return {
    code: 0,
    data: "Confirmation email sent!",
  };
};
